<?php

namespace app\models\user;

use Yii;

/**
 * This is the model class for table "user_cash".
 *
 * @property int $id
 * @property string $sn
 * @property int $user_id
 * @property float $amount 提现金额
 * @property float $service 服务费
 * @property int $status 0 未审核 1 已代付 -1 已驳回
 * @property string $reject 驳回原因
 * @property string $nickname 银行卡预留名字
 * @property string $bank_name 银行名称
 * @property string $bank_number 卡号
 * @property string $mobile 预留手机
 * @property string $create_time
 * @property string $update_time
 */
class UserCash extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_cash';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'status'], 'integer'],
            [['amount', 'service'], 'number'],
            [['service'], 'required'],
            [['create_time', 'update_time'], 'safe'],
            [['sn', 'nickname', 'bank_name', 'bank_number'], 'string', 'max' => 100],
            [['reject', 'mobile'], 'string', 'max' => 255],

            [['bank_x'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sn' => 'Sn',
            'user_id' => 'User ID',
            'amount' => 'Amount',
            'service' => 'Service',
            'status' => 'Status',
            'reject' => 'Reject',
            'nickname' => 'Nickname',
            'bank_name' => 'Bank Name',
            'bank_number' => 'Bank Number',
            'mobile' => 'Mobile',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public static function generateSn()
    {
        do {
            $sn = date('YmdHis') . mt_rand(10000, 99999);
        } while(self::findOne(['sn' => $sn]));

        return $sn;
    }
}
